<template>
  <el-button
      type="primary"
      :style="`width:${realWidth};height:${realHeight};`"
      @click="downloadFile"
  >
    <slot>{{ fileName || '下载文件' }}</slot>
  </el-button>
</template>

<script setup>
import { computed } from "vue";

const props = defineProps({
  src: {       // 文件路径或 URL
    type: String,
    required: true
  },
  fileName: {  // 下载时显示的文件名，可选
    type: String,
    default: ""
  },
  width: {
    type: [String, Number],
    default: ""
  },
  height: {
    type: [String, Number],
    default: ""
  }
});

// 拼接完整 URL（如果是外部链接则直接用，如果是相对路径拼接 API 前缀）
const realSrc = computed(() => {
  if (!props.src) return "";
  if (props.src.startsWith("http") || props.src.startsWith("/")) {
    return props.src;
  }
  return import.meta.env.VITE_APP_BASE_API + props.src;
});

const realWidth = computed(() =>
    typeof props.width === "string" ? props.width : `${props.width}px`
);
const realHeight = computed(() =>
    typeof props.height === "string" ? props.height : `${props.height}px`
);

// 下载函数
const downloadFile = () => {
  const link = document.createElement("a");
  link.href = realSrc.value;
  link.download = props.fileName || realSrc.value.split("/").pop();
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};
</script>

<style scoped>
.el-button {
  border-radius: 5px;
}
</style>
